package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.Utility;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.img.ImageLoader;

public class UserProfileMd implements OnTouchListener{
	MainActivity activity 	= null;
	Thread httpThread = null;
	Handler mHandler = new Handler();		

	@SuppressLint("HandlerLeak")
	Handler mMainHandler = new Handler() {

		public void handleMessage(Message msg) {        	 

		}

	};

	public void sendMessage(String msg){
		Message mssg = new Message();
		mssg.obj = msg;
		mMainHandler.sendMessage(mssg);
	}
	

	UserProfileCallback upcallback = null;
	public interface UserProfileCallback {
		public void callback();
	}
	
	public void setProfileSavedCallback(UserProfileCallback upcallback){
		this.upcallback = upcallback;
	}

	public void init(MainActivity activity){
		this.activity = activity;
		
		ImageView user_pf_img_genre_dence = (ImageView) activity.findViewById(R.id.user_pf_img_genre_dence);
		user_pf_img_genre_dence.setOnTouchListener(this);
		ImageView user_pf_img_genre_electronic = (ImageView) activity.findViewById(R.id.user_pf_img_genre_electronic);
		user_pf_img_genre_electronic.setOnTouchListener(this);
		ImageView user_pf_img_genre_house = (ImageView) activity.findViewById(R.id.user_pf_img_genre_house);
		user_pf_img_genre_house.setOnTouchListener(this);
		ImageView user_pf_img_genre_pop = (ImageView) activity.findViewById(R.id.user_pf_img_genre_pop);
		user_pf_img_genre_pop.setOnTouchListener(this);
		ImageView user_pf_img_genre_rb = (ImageView) activity.findViewById(R.id.user_pf_img_genre_rb);
		user_pf_img_genre_rb.setOnTouchListener(this);
		ImageView user_pf_img_genre_jazz = (ImageView) activity.findViewById(R.id.user_pf_img_genre_jazz);
		user_pf_img_genre_jazz.setOnTouchListener(this);
		ImageView user_pf_img_genre_hiphop = (ImageView) activity.findViewById(R.id.user_pf_img_genre_hiphop);
		user_pf_img_genre_hiphop.setOnTouchListener(this);
		ImageView user_pf_img_genre_rock = (ImageView) activity.findViewById(R.id.user_pf_img_genre_rock);
		user_pf_img_genre_rock.setOnTouchListener(this);
		
		ImageView user_pf_img_genre_metal = (ImageView) activity.findViewById(R.id.user_pf_img_genre_metal);
		user_pf_img_genre_metal.setOnTouchListener(this);
		ImageView user_pf_img_genre_classical = (ImageView) activity.findViewById(R.id.user_pf_img_genre_classical);
		user_pf_img_genre_classical.setOnTouchListener(this);
		ImageView user_pf_img_genre_newage = (ImageView) activity.findViewById(R.id.user_pf_img_genre_newage);
		user_pf_img_genre_newage.setOnTouchListener(this);
		ImageView user_pf_img_genre_folk = (ImageView) activity.findViewById(R.id.user_pf_img_genre_folk);
		user_pf_img_genre_folk.setOnTouchListener(this);
		ImageView user_pf_img_genre_latin = (ImageView) activity.findViewById(R.id.user_pf_img_genre_latin);
		user_pf_img_genre_latin.setOnTouchListener(this);
		ImageView user_pf_img_genre_reggage = (ImageView) activity.findViewById(R.id.user_pf_img_genre_reggage);
		user_pf_img_genre_reggage.setOnTouchListener(this);
		ImageView user_pf_img_genre_reli = (ImageView) activity.findViewById(R.id.user_pf_img_genre_reli);
		user_pf_img_genre_reli.setOnTouchListener(this);
		ImageView user_pf_img_genre_other = (ImageView) activity.findViewById(R.id.user_pf_img_genre_other);
		user_pf_img_genre_other.setOnTouchListener(this);
		
	
	}

	public void showUserProfile(){				
		
		LinearLayout layout_user_profile = (LinearLayout) activity.findViewById(R.id.layout_user_profile);
		layout_user_profile.setVisibility(View.VISIBLE);

		SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE); 
		String fbId 		= prefs.getString(FacebookMd.PREFERENCE_USER_FB_ID, "");
		String fbFirstNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
		String fbLastNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
		String fbPicUrl 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, "");

		if(fbPicUrl.length() < 1){
			Bundle params = new Bundle();
			params.putString(Facebook.TOKEN, Session.getActiveSession().getAccessToken());
			params.putString("fields", "name, picture, email");
			Utility.mAsyncRunner.request("me", params, new UserRequestListener());
		}
		
		TextView user_pf_username = (TextView) activity.findViewById(R.id.user_pf_username);
		user_pf_username.setText(fbFirstNm + " " +fbLastNm);

		AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
		ab.setMessage("버튼을 눌러 관심장르와 대표장르를 선택해 주세요.");  
		ab.setPositiveButton("ok", null);  
		ab.show();  
		
		TextView btn_top_right = (TextView) activity.findViewById(R.id.btn_top_right_text);
		btn_top_right.setText("save");
		ImageView btn_top_right_img = (ImageView) activity.findViewById(R.id.btn_top_right_img);
		btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				ImageView imgView = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					imgView.setPadding(2, 2, 2, 2);
					imgView.setColorFilter(0xaa111111,Mode.SRC_OVER);
				}else if(event.getAction() == MotionEvent.ACTION_UP){	
					
					saveUserProfile();
					
					imgView.setPadding(0, 0, 0, 0);
					imgView.setColorFilter(0x00000000, Mode.SRC_OVER);
				}else if(event.getAction() == MotionEvent.ACTION_CANCEL){
					
					imgView.setPadding(0, 0, 0, 0);
					imgView.setColorFilter(0x00000000, Mode.SRC_OVER);
				}
				
				return true;
			}
		});
	}
	
	String clubName = null;
	ArrayList<String> interGenres = null;
	ArrayList<String> rpGenres = null;
	
	public static String arrayJoin(String glue, ArrayList<String> array) {
		String result = "";

		for (int i = 0; i < array.size(); i++) {
			result += array.get(i);
			if (i < array.size() - 1) result += glue;
		}
		return result;
	}


	
	public void saveUserProfile(){
		
		// 관심장르 채크
		LinearLayout inGenresLayout = (LinearLayout) activity.findViewById(R.id.user_interest_genres);			
		interGenres = new ArrayList<String>();
		
		for(int k = 0; k < inGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)inGenresLayout.getChildAt(k);
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				
				if(tcheck != null && tcheck.getVisibility() == View.VISIBLE){					
					interGenres.add((String)fLayout.getContentDescription());
				}				
			}								
		}
		
		// 대표장르 채크
		LinearLayout rpGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);			
		rpGenres = new ArrayList<String>();
		
		for(int k = 0; k < rpGenresLayout.getChildCount(); k++){
			LinearLayout root = (LinearLayout)rpGenresLayout.getChildAt(k);
			for(int i = 0; i < root.getChildCount(); i++){
				FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
				ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
				
				if(tcheck != null && tcheck.getVisibility() == View.VISIBLE){
					rpGenres.add((String)fLayout.getContentDescription());
					k = rpGenresLayout.getChildCount();
					break;
				}				
			}								
		}
		
		// 클럽명 채크		
		EditText cnView = (EditText) activity.findViewById(R.id.user_pf_clubname);
		clubName = cnView.getText().toString();
		
		if(clubName != null && clubName.length() < 1){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
			ab.setMessage("클럽명을 넣어주세요.");  
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else if(interGenres.size() < 1){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
			ab.setMessage("관심장르를 선택해 주세요.");  
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else if(rpGenres.size() < 1){
			AlertDialog.Builder ab=new AlertDialog.Builder(activity);  
			ab.setMessage("대표장르를 선택해 주세요.");  
			ab.setPositiveButton("ok", null);  
			ab.show();
		}else{
			// 완벽하다면..
			
			int timeout = 3;
			new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
				
				@Override
				public void fail(Object result) {
					// TODO Auto-generated method stub
					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
					ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
					ab.setPositiveButton("ok", null);  
					ab.show();
				}
				
				@Override
				public void sucess(Object result){
//					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
//					ab.setMessage("저장되었습니다.");					
//					ab.setPositiveButton("ok", null);  
//					ab.show();
					

					// 소스가 난리가 나서
					if(upcallback != null){
						upcallback.callback();
						upcallback = null;
					}
				}
				
				@Override
				public void threadProcess(ConnectThread resultset) throws Exception {
					// TODO Auto-generated method stub					
					HttpClient client = NetWorkManager.getHttpConnection();    
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

					HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/userSetting.php");
//					a.	user_type : 2
//					b.	uId : 유저 ID
//					c.	club_title : 스튜디오명
//					d.	main_genre : 메인장르
//					e.	genre_ids : 장르ID들 ( ex : 1,3,5,7,9 )

					String buserId = activity.facebookMd.getBonoUserId();
					
					if(buserId == null || clubName == null || buserId.length() < 1|| interGenres.size() < 1 || rpGenres.size() < 1){
						throw new Exception("parameter error");
					}
					
//					Log.e("#########uId", "########" + buserId);
//					Log.e("#########club_title", "########" + clubName);
//					Log.e("#########main_genre", "########" + rpGenres.get(0));
//					Log.e("#########genre_ids", "########" + arrayJoin(",",interGenres));
					
					List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
					params.add(new BasicNameValuePair("user_type", "2"));
					params.add(new BasicNameValuePair("uId", buserId));
					params.add(new BasicNameValuePair("club_title", clubName));
					params.add(new BasicNameValuePair("main_genre", rpGenres.get(0)));
					params.add(new BasicNameValuePair("genre_ids", arrayJoin(",",interGenres) ));
					
					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);  

					InputStream in = responsePOST.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					String jsonStr = str.toString();
					
					if(!"1".equals(jsonStr)){
						throw new Exception("fail");
					}else{
						activity.facebookMd.getUserInfo();
					}
					
				}
			}).start(); 
		}		
	}
	

	public class UserRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

				final String picURL = jsonObject.getJSONObject("picture")
						.getJSONObject("data").getString("url");
				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");
				
				
				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
				SharedPreferences.Editor editor = prefs.edit();					
				editor.putString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, picURL);
				editor.commit();

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						ImageView imageView = (ImageView) activity.findViewById(R.id.user_pf_pic);
						ImageLoader.download(picURL, imageView);
					}
				});

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}
	
	private int mAddTotalCnt = 0;
	LinearLayout mLineLayout =  null;
	
	public void addRepresentativeGenre(FrameLayout view){
		LinearLayout rpGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);

		// 네줄식 나눠 담기
		if(mAddTotalCnt % 4 == 0){
			mLineLayout = new LinearLayout(activity);
			mLineLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
					LinearLayout.LayoutParams.WRAP_CONTENT));
			mLineLayout.setOrientation(LinearLayout.HORIZONTAL);
		}
		
		FrameLayout fLayout = new FrameLayout(activity);
		fLayout.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
		                    LayoutParams.WRAP_CONTENT));
		
		fLayout.setTag(view.getTag());		
		fLayout.setContentDescription(view.getContentDescription());	
		fLayout.setClickable(true);
		fLayout.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				

				// all check remove
				LinearLayout rpGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);				
				for(int k = 0; k < rpGenresLayout.getChildCount(); k++){
					LinearLayout root = (LinearLayout)rpGenresLayout.getChildAt(k);
					for(int i = 0; i < root.getChildCount(); i++){
						FrameLayout fLayout = (FrameLayout)root.getChildAt(i);
						for(int j = 0; j < fLayout.getChildCount(); j++){
							ImageView tcheck = (ImageView)((FrameLayout)fLayout).getChildAt(1);
							tcheck.setVisibility(View.INVISIBLE);						
						}
					}								
				}
				
				// and than check
				ImageView genre = (ImageView)((FrameLayout)v).getChildAt(0);
				ImageView check = (ImageView)((FrameLayout)v).getChildAt(1);
				
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					genre.setPadding(2, 2, 2, 2);
					genre.setColorFilter(0xaa111111,Mode.SRC_OVER);				
				}else if(event.getAction() == MotionEvent.ACTION_UP){
					if(check.getVisibility() == View.INVISIBLE){
						check.setVisibility(View.VISIBLE);
					}else{
						check.setVisibility(View.INVISIBLE);
					}
				}
				genre.setPadding(0, 0, 0, 0);
				genre.setColorFilter(0x00000000, Mode.SRC_OVER);				
				return true;
			}
		});
		
			// imageview add
			ImageView imageGenre = new ImageView(view.getContext());
			View genreView = view.getChildAt(0);				
			imageGenre.setLayoutParams(genreView.getLayoutParams());			
			imageGenre.setImageResource(view.getResources().getIdentifier((String)genreView.getTag(), "drawable", activity.getPackageName()));

			// imageview add
			ImageView imageCheck = new ImageView(view.getContext());			
			View checkView = view.getChildAt(1);						
			imageCheck.setLayoutParams(checkView.getLayoutParams());			
			imageCheck.setImageResource(checkView.getResources().getIdentifier((String)checkView.getTag(), "drawable", activity.getPackageName()));
			imageCheck.setVisibility(View.INVISIBLE);
		
		fLayout.addView(imageGenre);
		fLayout.addView(imageCheck);
		
		if(mAddTotalCnt % 4 == 0){
			mLineLayout.addView(fLayout);		
			rpGenresLayout.addView(mLineLayout);
		}else{
			mLineLayout.addView(fLayout);
		}
		
		mAddTotalCnt++;
	}
	
	
	public void removeRepresentativeGenre(FrameLayout view){
		LinearLayout reGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);
		FrameLayout viewForRemove = null;
		LinearLayout linearLayout = null;
		for(int i = 0; i < reGenresLayout.getChildCount(); i++){
			linearLayout = (LinearLayout)reGenresLayout.getChildAt(i);			
			
			for(int j = 0; j < linearLayout.getChildCount(); j++){
				viewForRemove = (FrameLayout)linearLayout.getChildAt(j);
					
				if(view.getTag() != null && view.getTag().equals(viewForRemove.getTag())){
					i = reGenresLayout.getChildCount();
					break;
				}			
			}
		}		
		
		if(linearLayout !=null){
			linearLayout.removeView(viewForRemove);
			if(linearLayout.getChildCount() == 0){
				reGenresLayout.removeView(linearLayout);
			}
		}
		
		sortView(view);
		mAddTotalCnt--;
	}
	
	public void sortView(FrameLayout view){
		LinearLayout reGenresLayout = (LinearLayout) activity.findViewById(R.id.user_rp_genres);
		LinearLayout beforeLayout = null;
		for(int i = 0; i < reGenresLayout.getChildCount(); i++){
			beforeLayout = (LinearLayout)reGenresLayout.getChildAt(i);
			
			if(beforeLayout.getChildCount() < 4){
				
				// 다음 레이아웃이 있다면
				if(i + 1 != reGenresLayout.getChildCount()){
					LinearLayout nextLayout = (LinearLayout)reGenresLayout.getChildAt(i + 1);
										
					View viewToInsert = nextLayout.getChildAt(0);
					nextLayout.removeView(viewToInsert);
					beforeLayout.addView(viewToInsert);
					
					// 뷰가없다면 지운다.
					if(nextLayout.getChildCount() == 0){
						reGenresLayout.removeView(nextLayout);
					}
				}
				
			}		
		}	
	}

	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		ImageView view = (ImageView)v;
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			view.setPadding(2, 2, 2, 2);
			view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
		}else if(event.getAction() == MotionEvent.ACTION_UP){
			
			FrameLayout flayout = (FrameLayout)v.getParent();
			
			if(flayout.getChildAt(1).getVisibility() == View.INVISIBLE){
				flayout.getChildAt(1).setVisibility(View.VISIBLE);						
				addRepresentativeGenre(flayout);
				
			}else{
				flayout.getChildAt(1).setVisibility(View.INVISIBLE);
				removeRepresentativeGenre(flayout);
			}
			
			switch(v.getId()){
				case R.id.user_pf_img_genre_dence:
										
					break;				
			}
			
			
			
			view.setPadding(0, 0, 0, 0);
			view.setColorFilter(0x00000000, Mode.SRC_OVER);			
		}else if(event.getAction() == MotionEvent.ACTION_CANCEL){
			view.setPadding(0, 0, 0, 0);
			view.setColorFilter(0x00000000, Mode.SRC_OVER);
		}
		return true;
	}



	public void onClick(View v,Messenger mMessenger,Messenger mService ){

	}

	public void hideUserProfile() {
		// TODO Auto-generated method stub
		LinearLayout layout_user_profile = (LinearLayout) activity.findViewById(R.id.layout_user_profile);
		layout_user_profile.setVisibility(View.GONE);		
	}
}
